package atguigu.mqtt;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class Demo1 {

    public static void main(String[] args) {
        String topic = "aaa";
        String content = "Hello World";
        int qos = 2;
        String broker = "ssl://kbb411ee.ala.cn-hangzhou.emqxsl.cn:8883";
        String clientId = MqttClient.generateClientId();
        // 持久化
        MemoryPersistence persistence = new MemoryPersistence();
        // MQTT 连接选项
        MqttConnectOptions connOpts = new MqttConnectOptions();
        // 设置认证信息
        connOpts.setUserName("yejing");
        connOpts.setPassword("MZD1893,".toCharArray());
        // 设置CA证书
        try {
//            String caCrtFile = Demo1.class.getResource("").getPath() + "./emqxsl-ca.crt";
            String caCrtFile = "E:\\软件\\emqxsl-ca.crt";
            connOpts.setSocketFactory(SSLUtils.getSingleSocketFactory(caCrtFile));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        try(MqttClient client = new MqttClient(broker, clientId, persistence);){
            // 设置回调
            client.setCallback(new SampleCallback());
            // 建立连接
            System.out.println("Connecting to broker: " + broker);
            client.connect(connOpts);
            System.out.println("Connected to broker: " + broker);

            // 发布消息
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(qos);
            client.publish(topic, message);
            System.out.println("Message published");

        }catch (MqttException e){
            e.printStackTrace();
        }

    }
}
